import ColorUISdk from '../../mp-sdk/index'

// 定义接口类型
interface UploadResult {
  url: string;
}

interface UploadResponse {
  code: 0 | number;
  data?: UploadResult;
  msg?: string;
}

interface BuildingInfo {
  id: string;
  record_id: string;
  name: string;
  description: string;
  type?: string; // 新增：建筑类型
}

interface IdentifyResponse {
  code: 0 | number;
  data?: BuildingInfo;
  msg?: string;
}

interface RecordItem {
  id: string;
  image_url: string;
  building_name: string;
  building_description: string;
  saved: boolean;
  created_at: string;
}

interface RecordsResponse {
  code: 0 | number;
  data?: {
    records: RecordItem[];
    total: number;
    page: number;
    limit: number;
  };
  msg?: string;
}

const sdk = new ColorUISdk({
  env: 'dev',
  version: '1.0.0',
  api: {
    dev: { 
      // url: 'http://172.20.10.2:5000'
      // url:'http://127.0.0.1:5000'
      url:'http://192.168.134.31:5000'
    }
  }
})

Page({
  data: {
    showResult: false,
    resultImage: '', // 拍照后的临时图片路径
    buildingInfo: {
      id: '',
      record_id: '',
      name: '',
      description: '',
      type: ''
    } as BuildingInfo,
    isIdentifying: false,
    imageUrl: '', // 上传后的图片URL
    showCamera: false, // 控制相机显示
    cameraContext: null as WechatMiniprogram.CameraContext | null, // 相机上下文
    showHistoryModal: false,
    historyRecords: [] as RecordItem[],
    currentPage: 1,
    totalRecords: 0,
    hasMore: true,
    description: ''
  },

  onLoad() {
    // 检查是否从AR页面跳转回来且带有建筑信息
    const options = wx.getLaunchOptionsSync().query;
    if (options.fromAR && options.buildingName) {
      this.setData({
        showResult: true,
        buildingInfo: {
          ...this.data.buildingInfo,
          name: decodeURIComponent(options.buildingName)
        }
      });
    }
    
    // 检查相机权限
    this.checkCameraPermission()
  },

  onReady() {
    // 页面准备好后创建相机上下文
    this.setData({
      cameraContext: wx.createCameraContext()
    })
  },

  // 检查相机权限
  checkCameraPermission(callback?: () => void) {
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.camera']) {
          wx.authorize({
            scope: 'scope.camera',
            success: () => {
              console.log('相机授权成功')
              callback && callback()
            },
            fail: () => {
              wx.showModal({
                title: '权限申请',
                content: '需要相机权限才能使用拍照功能',
                success: (modalRes) => {
                  if (modalRes.confirm) {
                    wx.openSetting()
                  }
                }
              })
            }
          })
        } else {
          callback && callback()
        }
      }
    })
  },

  onCameraError(e: WechatMiniprogram.CameraError) {
    console.error('相机错误:', e.detail)
    wx.showToast({
      title: '相机打开失败',
      icon: 'none'
    })
    this.setData({ showCamera: false })
  },

  // 打开相机
  openCamera() {
    if (this.data.isIdentifying) return
    
    this.checkCameraPermission(() => {
      this.setData({ showCamera: true })
    })
  },

  // 关闭相机
  closeCamera() {
    this.setData({ showCamera: false })
  },

  // 拍照并保存
  takePhoto() {
    if (this.data.isIdentifying) return
    
    const ctx = this.data.cameraContext || wx.createCameraContext()
    if (!ctx) {
      wx.showToast({
        title: '相机初始化失败',
        icon: 'none'
      })
      return
    }
    
    ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        // 拍照成功后保存到相册
        wx.saveImageToPhotosAlbum({
          filePath: res.tempImagePath,
          success: () => {
            wx.showToast({
              title: '照片保存成功',
              icon: 'success'
            })
            
            // 关闭相机并设置图片路径
            this.setData({
              resultImage: res.tempImagePath,
              showCamera: false
            })
          },
          fail: (err) => {
            console.error('保存照片失败:', err)
            wx.showToast({
              title: '保存照片失败',
              icon: 'none'
            })
          }
        })
      },
      fail: (err) => {
        console.error('拍照失败:', err)
        wx.showToast({
          title: '拍照失败',
          icon: 'none'
        })
      }
    })
  },

  // 从相册选择
  chooseImage() {
    if (this.data.isIdentifying) return
    
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album'],
      success: (res) => {
        this.setData({
          resultImage: res.tempFilePaths[0]
        })
      }
    })
  },

  // 移除已选图片
  removeImage() {
    this.setData({
      resultImage: '',
      imageUrl: '',
      showResult: false,
      description: '',
      buildingInfo: {
        id: '',
        record_id: '',
        name: '',
        description: '',
        type: ''
      }
    })
  },

  // 开始识别
  startIdentify() {
    if (!this.data.resultImage || this.data.isIdentifying) return
    
    this.identifyBuilding(this.data.resultImage)
  },

  // 建筑识别
  async identifyBuilding(imagePath: string) {
    this.setData({ isIdentifying: true })
    
    try {
      wx.showLoading({ title: '识别中...', mask: true })
      
      // 先上传图片到uploads目录
      const uploadRes = await this.uploadImage(imagePath)
      
      if (!uploadRes || !uploadRes.url) {
        wx.hideLoading()
        this.setData({ isIdentifying: false })
        wx.showToast({
          title: '图片上传失败',
          icon: 'none'
        })
        return
      }
      
      // 保存上传后的图片URL
      this.setData({ imageUrl: uploadRes.url })
      
      // 获取token
      const token = wx.getStorageSync('token')
      if (!token) {
        wx.hideLoading()
        this.setData({ isIdentifying: false })
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        })
        wx.navigateTo({ url: '/pages/login/login' })
        return
      }
      
      // 调用识别接口
      const res = await sdk.request({
        url: '/api/building/identify',
        method: 'POST',
        header: {
          'Authorization': `Bearer ${token}`
        },
        data: {
          imageUrl: uploadRes.url,
          description: this.data.description
        }
      }) as IdentifyResponse
      
      wx.hideLoading()
      
      if (res.code === 0 && res.data) {
        this.setData({
          showResult: true,
          buildingInfo: res.data
        })
        
        // 暂存识别结果到本地存储
        wx.setStorageSync('lastBuildingInfo', res.data);
      } else {
        wx.showToast({
          title: res.msg || '识别失败，请重试',
          icon: 'none'
        })
      }
    } catch (error: any) {
      wx.hideLoading()
      console.error('识别错误:', error)
      
      let errorMsg = '识别失败，请重试'
      if (typeof error === 'object' && error !== null && 'errMsg' in error) {
        errorMsg = error.errMsg.includes('timeout') ? '识别超时，请重试' : error.errMsg
      }
      
      wx.showToast({ 
        title: errorMsg, 
        icon: 'none',
        duration: 3000
      })
    } finally {
      this.setData({ isIdentifying: false })
    }
  },

  // 上传图片到服务器uploads目录
  uploadImage(tempFilePath: string) {
    return new Promise<UploadResult | undefined>((resolve, reject) => {
      // 使用sdk配置的基础URL，解决真机无法访问127.0.0.1的问题
      const uploadUrl = `${sdk.api.dev.url}/api/upload`;
      
      wx.uploadFile({
        url: uploadUrl, 
        filePath: tempFilePath,
        name: 'file',
        header: {
          'Authorization': `Bearer ${wx.getStorageSync('token') || ''}`
        },
        success: (res) => {
          try {
            // 处理可能的空响应
            if (!res.data) {
              reject('上传响应为空')
              return
            }
            
            const data: UploadResponse = JSON.parse(res.data)
            if (data.code === 0 && data.data) {
              // 验证图片URL是否有效，使用sdk的基础URL
              const verifyUrl = `${sdk.api.dev.url}${data.data.url}`;
              wx.request({
                url: verifyUrl,
                method: 'HEAD',
                success: () => resolve(data.data),
                fail: (err) => {
                  console.error('图片上传后验证失败:', err)
                  reject('图片上传失败，请重试')
                }
              })
            } else {
              reject(data.msg || '上传失败')
            }
            } catch (e) {
            console.error('解析上传响应失败:', e)
            reject('解析响应失败')
          }
        },
        fail: (err) => {
          reject(err)
        }
      })
    })
  },

  closeResult() {
    this.setData({
      showResult: false
    })
  },

  // 保存识别记录
  async saveRecord() {
    const { record_id } = this.data.buildingInfo
    const token = wx.getStorageSync('token')
    
    if (!token || !record_id) return false
    
    try {
      wx.showLoading({ title: '保存中...' })
      
      const res = await sdk.request({
        url: `/api/records/save/${record_id}`,
        method: 'POST',
        header: {
          'Authorization': `Bearer ${token}`
        }
      }) as any
      
      wx.hideLoading()
      
      if (res.code === 0) {
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        })
      } else {
        wx.showToast({
          title: res.msg || '保存失败',
          icon: 'none'
        })
      }
    } catch (error) {
      wx.hideLoading()
      console.error('保存记录失败:', error)
      wx.showToast({
        title: '保存失败',
        icon: 'none'
      })
    }
  },

  // 前往AR页面
  gotoAR() {
    const { name, id, type } = this.data.buildingInfo
    if (name) {
      wx.navigateTo({
        url: `/pages/ar-culture/ar-culture?buildingName=${encodeURIComponent(name)}&buildingId=${id}&buildingType=${type || ''}`
      })
    }
  },

  // 前往打卡页面
  gotoCheckin() {
    const { name, id } = this.data.buildingInfo
    if (name && id) {
      wx.navigateTo({
        url: `/pages/checkin/checkin?buildingName=${encodeURIComponent(name)}&buildingId=${id}`
      })
    }
  },

  // 显示历史记录
  showHistory() {
    this.setData({
      showHistoryModal: true,
      currentPage: 1,
      historyRecords: [],
      hasMore: true
    }, () => {
      this.loadMoreRecords()
    })
  },

  // 关闭历史记录弹窗
  closeHistoryModal() {
    this.setData({
      showHistoryModal: false
    })
  },

  // 加载更多历史记录
  async loadMoreRecords() {
    if (this.data.isIdentifying || !this.data.hasMore) return
    
    this.setData({ isIdentifying: true })
    
    const token = wx.getStorageSync('token')
    const { currentPage } = this.data
    
    try {
      const res = await sdk.request({
        url: `/api/records?page=${currentPage}&limit=10`,
        method: 'GET',
        header: {
          'Authorization': `Bearer ${token}`
        }
      }) as RecordsResponse
      
      if (res.code === 0 && res.data) {
        const { records, total, page: currentPage } = res.data
        this.setData({
          historyRecords: currentPage === 1 ? records : [...this.data.historyRecords, ...records],
          totalRecords: total,
          currentPage,
          hasMore: currentPage * 10 < total
        })
      } else {
        wx.showToast({
          title: res.msg || '获取记录失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('获取历史记录失败:', error)
      wx.showToast({
        title: '获取记录失败',
        icon: 'none'
      })
    } finally {
      this.setData({ isIdentifying: false })
    }
  },

  // 切换记录保存状态
  async toggleSaveRecord(e: any) {
    const { id, saved } = e.currentTarget.dataset
    const token = wx.getStorageSync('token')
    
    if (!token || !id) return
    
    try {
      wx.showLoading({ title: saved ? '取消保存中...' : '保存中...' })
      
      const url = saved 
        ? `/api/records/unsave/${id}`
        : `/api/records/save/${id}`
      
      const res = await sdk.request({
        url,
        method: 'POST',
        header: {
          'Authorization': `Bearer ${token}`
        }
      }) as any
      
      wx.hideLoading()
      
      if (res.code === 0) {
        wx.showToast({
          title: saved ? '取消保存成功' : '保存成功',
          icon: 'success'
        })
        
        // 更新本地记录状态
        const updatedRecords = this.data.historyRecords.map(record => 
          record.id === id ? { ...record, saved: !saved } : record
        )
        
        this.setData({
          historyRecords: updatedRecords
        })
      } else {
        wx.showToast({
          title: res.msg || '操作失败',
          icon: 'none'
        })
      }
    } catch (error) {
      wx.hideLoading()
      console.error('操作记录失败:', error)
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      })
    }
  },

  // 输入描述
  onDescriptionInput(e: { detail: { value: string } }) {
    this.setData({
      description: e.detail.value
    })
  }
})